<template>
  <div class="anvil-code-filling-container">
    <form-render
      v-if="isShowForm"
      :key="formRenderKey"
      v-model:data="editForm.formData"
      :options="editForm.formJsonOption"
      :pageId="pageId"
      ref="form"
      @close-and-refresh="emitCloseAndRefresh"
      @close-and-set="emitCloseAndSet"
      @only-close="emitOnlyClose"
    />
    <el-skeleton v-else animated :rows="5"></el-skeleton>
  </div>
</template>

<script>
import { handleFormDataTrans, handleFormDataTransBack, generateFormRules, specialSignTrans, executeFunctionsInOrderByParamsSetting, getJsonCallableCompList, getJsonCallableCompListWithChildren } from '../../../utils/common-methods';
import FormRender from '../../form-render/index.vue';
import { useUserStore } from '@/store/modules/user';
import { searchFormByPageId } from '../../../api/page';
import { useAnvilCodeStore } from '../../../store/modules/code';
import { getToken } from '@/utils/auth';
import { Base64 } from 'js-base64';
import { isBase64 } from '@/utils/zmids'
import EventsMap from '../../../components/EventsMap';
import emitsMixin from '@code/components/anvil-code-low-common/mixins/emitsMixin';

export default {
  name: 'PageFilling',
  components: { FormRender },
  mixins: [emitsMixin],
  props: {
    targetPageId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      editForm: {},
      pageId: '',
      allEventsByComps: [],
      formRenderKey: '' // 用于强制更新表单
    };
  },
  computed: {
    // 确保在formjson获取完毕后渲染表单
    isShowForm() {
      return (
        this.editForm.formJsonOption &&
        ((this.editForm.formJsonOption.column && this.editForm.formJsonOption.column.length) || (this.editForm.formJsonOption.group && this.editForm.formJsonOption.group.length))
      );
    }
  },
  async created() {
    this.initVars();
    const { autoSsoLogin, getInfo } = useUserStore();
    if (this.$route.query.token) {
      await autoSsoLogin(this.$route.query.token);
    }else{
      await getInfo();
    }
    this.init();
  },
  beforeUnmount() {
    this.removeListener();
  },
  methods: {
    initData() {
      // this.pageId = ''
      this.editForm = {
        // 是否修改操作
        isModify: false,
        // 页面数据
        formData: {},
        // 渲染JSON
        formJsonOption: {
          column: []
        }
      };
    },
    initVars() {
      if (this.targetPageId) {
        this.pageId = this.targetPageId;
        return;
      }
      const { pageId } = this.$route.params;
      if (pageId) {
        this.pageId = pageId;
      }
      const { setSpaUniCode } = useAnvilCodeStore();
      setSpaUniCode(this.pageId);
    },
    // closeAndRefresh() {
    //   console.log('filling页面接收到close-and-refresh');
    //   this.$emit('closeAndRefresh');
    // },
    // 获取页面配置信息
    async getConfigInfo(pageId) {
      // Form渲染JSON
      this.editForm.formJsonOption = {};
      var formJsonData = await searchFormByPageId(this.pageId);
      if (formJsonData && formJsonData.data) {
        let { pageFormJson } = formJsonData.data
        if(isBase64(pageFormJson)){
          pageFormJson = Base64.decode(pageFormJson);
        }
        const json = specialSignTrans(pageFormJson);
        const options = JSON.parse(json);
        this.getFormJsonOption(options);
        this.editForm.formJsonOption = options;
      }
    },
    getFormJsonOption(options) {
      const compArr = getJsonCallableCompListWithChildren(options)
      compArr.map((comp)=>{
        this.handleFuncStrTransform(comp);
      })
      return compArr
    },
    // 处理方法字符串中的=>转义问题
    handleFuncStrTransform(item) {
      this.allEventsByComps.forEach((event) => {
        if (item[event] && typeof item[event] == 'string') {
          // 先对str做转义处理
          const str = item[event].replaceAll('&gt;', '>');
          item[event] = eval('(' + str + ')');
        } else if (item[`_${event}`] && typeof item[`_${event}`] == 'object') {
          const { params, components } = item[`_${event}`];
          // 挂载调用函数,这里不能使用箭头函数，调用时this必须是组件自己的实例对象
          item[event] = function () {
            executeFunctionsInOrderByParamsSetting(this, params, components, true);
          };
          delete item[`_${event}`];
        }
      });
    },
    getAllEventsByComps() {
      const events = [];
      for (let name in EventsMap) {
        const e = EventsMap[name].map((item) => item.value);
        events.push(...e);
      }
      this.allEventsByComps = [...new Set(events)];
    },
    // 支持在url中给表单传默认值
    getDefaultFormData() {
      const { query } = this.$route;
      for (let key in query) {
        const isExist = this.editForm.formJsonOption.column.find((item) => item.prop == key);
        if (isExist) {
          this.editForm.formData[key] = query[key];
        }
      }
    },
    // 监听跨域iframe传递过来的事件参数
    listenPostMessage(message) {
      try {
        const { data } = message;
        if (typeof data !== 'string') {
          return;
        }
        console.log('接收到了iframe传参', data);
        const postObj = JSON.parse(Base64.decode(data));
        console.log('接收到了iframe传参', postObj);
        const { type, params } = postObj;

        if (type == 'push') {
          const { path, query } = params;
          this.$router.push({ path, query });
        } else if (type == 'refresh') {
          // 调用表单的刷新事件
          this.$refs.form.refresh();
        }
      } catch (e) {
        console.log('error!', e);
      }
    },
    addListener() {
      window.addEventListener('message', this.listenPostMessage);
    },
    removeListener() {
      window.removeEventListener('message', this.listenPostMessage);
    },
    async init() {
      this.getAllEventsByComps();
      this.addListener();
      this.initData();
      await this.getConfigInfo();
    },
    // 强制更新表单
    updateFormRender() {
      this.formRenderKey = Math.random().toString(36).substring(2, 9);
    }
  }
};
</script>
